﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using Obsidian.Utils;
using System.Xml;
using Obsidian.Utils;

namespace Obsidian.Config
{
    public class ErrorPageConifg
    {

        private static DateTime modified = DateTime.MinValue;
        private static ErrorPageInfo errorPage;
        private static Hashtable htErrorPage = Hashtable.Synchronized(new Hashtable());

        public static ErrorPageInfo GetErrorPage(string status)
        {
            CheckForChanged();
            if (!htErrorPage.ContainsKey(status))
                throw new Exception("配置项 appConfig/errorPages/page status:" + status + " 不存在");

            ErrorPageInfo errorPage = (ErrorPageInfo)htErrorPage[status];
            if (String.IsNullOrEmpty(errorPage.Url))
                throw new Exception("配置项 appConfig/errorPages/page url属性不能为空");

            return errorPage;
        }

        public static bool HasStatus(string status)
        {
            CheckForChanged();
            return htErrorPage.ContainsKey(status);
        }

        private static void CheckForChanged()
        {
            if (AppConfig.CheckForChanged() || !AppConfig.Modified.Equals(modified))
            {
                GetErrorPages();
                modified = AppConfig.Modified;
            }
        }

        private static void GetErrorPages()
        {
            lock (htErrorPage)
            {
                htErrorPage.Clear();
                XmlDocument xmlDoc = AppConfig.GetXml();
                XmlNodeList nodeList = xmlDoc.SelectNodes("appConfig/errorPages/page");
                foreach (XmlNode node in nodeList)
                {
                    string status;
                    if (!XmlUtil.TryGetAttrValue(node, "status", out status)
                        || String.IsNullOrEmpty(status))
                        throw new Exception("配置项 appConfig/errorPages/page status属性不能为空");

                    string url;
                    XmlUtil.TryGetAttrValue(node, "url", out url);


                    ErrorPageInfo info = new ErrorPageInfo(status, url);
                    if (htErrorPage.ContainsKey(status))
                        throw new Exception("配置项 appConfig/errorPages/page status属性出现重复值:" + status);

                    htErrorPage.Add(status, info);
                }
            }
        }


        public class ErrorPageInfo
        {
            private string status;
            private string url;

            internal ErrorPageInfo(string status, string url)
            {
                this.status = status;
                this.url = url;
            }

            public string Status
            {
                get { return status; }
            }

            public string Url
            {
                get { return url; }
            }

        }

    }
}
